<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>案列测试</title>
    <link rel="stylesheet" href="../../layui/css/layui.css">
</head>
<body>
   
    <!--* 搜索开始 -->
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
      <legend>搜索条件</legend></legend>
    </fieldset>
    <form class="layui-form" action="" method="POST">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">用户ID</label>
          <div class="layui-input-inline">
            <input type="text" name="userId"  id="userIdSearch" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">用户名</label>
          <div class="layui-input-inline">
            <input type="text" name="userName" id="userNameSearch" class="layui-input">
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label" >开始时间</label>
          <div class="layui-input-inline">
            <input type="text" name="startTime"  id="startTimeSearch" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">结束时间</label>
          <div class="layui-input-inline">
            <input type="text" name="endTime" id="endTimeSearch" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-search" id="doSearch">搜索</button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">重置</button>
        </div>
      </div>  
    </form>
    <!--* 搜索结束 -->
    <!--TODO 主体就这一行 数据在script动态绑定-->
    <table class="layui-hide" id="test" lay-filter="test"></table>

    <!--* 工具栏  -->
    <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">增加</button>
        <button class="layui-btn layui-btn-sm" lay-event="batchDelete">批量删除</button>
      </div>
    </script>
    <!--* 工具条 -->
    <script type="text/html" id="barDemo">
      <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>


    <!--* 添加修改的弹出层开始  -->
    
    <div style="display:none; padding: 20px;" id="saveOrUpdateDiv">
        <form class="layui-form" action="" lay-filter="dataForm" id="dataForm">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">用户ID</label>
            <div class="layui-input-inline">
              <input type="text" style="display: none;" name="id" class="layui-input">
              <input type="text" name="userId"   lay-verify="required" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
              <input type="text" name="userName"  lay-verify="required" class="layui-input">
            </div>
          </div>
        </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">手机</label>
          <div class="layui-input-inline">
            <input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">邮箱</label>
          <div class="layui-input-inline">
            <input type="text" name="userEmail" lay-verify="email" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">设备ID</label>
          <div class="layui-input-inline">
            <input type="text" name="deviceId"  class="layui-input" placeholder="请输入设备ID">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">密码框</label>
           <div class="layui-input-inline">
            <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
           </div>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: right;">
        <div class="layui-inline" >
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release" lay-submit lay-filter="doSubmit"> 提交</button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh"> 重置</button>
        </div>
      </div>  
    </form>  
  </div>
 
    
    <!--* 添加修改的弹出层结束  -->
              
    <script src="../../layui/dist/layui.js" charset="utf-8"></script>
    <!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 --> 
    <script src="../../layui/jquery-1.8.3.min.js"></script>
    <script src="../../js/core.util.js"></script>
    <script>
    layui.use(['table','jquery','layer','form','table','laydate'], function(){
      var table = layui.table,
              $ = layui.jquery,
          layer = layui.layer,
           form = layui.form,
        laydate = layui.laydate;
      //绑定时间选择器
      laydate.render({
        elem:'#startTimeSearch'
      });
      laydate.render({
        elem:'#endTimeSearch'
      });


      //温馨提示：默认由前端自动合计当前行数据。从 layui 2.5.6 开始： 若接口直接返回了合计行数据，则优先读取接口合计行数据。
      //详见：https://www.layui.com/doc/modules/table.html#totalRow    /layui/table.json
    var tableIns =  table.render({
        elem: '#test'
        ,url:'http://localhost:8081/user/list',
        headers: {
               'userTicket':sessionStorage.getItem("userTicket"),
          }
        ,toolbar: '#toolbarDemo'
        ,title: '用户数据表'
        ,totalRow: false
        ,limits:[5,10,20,30]
        // ,height: 'full-200' //高度最大化减去差值
        ,cols: [[
          {type: 'checkbox', fixed: 'left'}
          ,{field:'userId', title:'用户ID', width:120 , sort: true}
          ,{field:'userName', title:'用户名', width:120}
          ,{field:'userEmail', title:'邮箱', width:150, templet: function(res){
            return '<em>'+ res.userEmail +'</em>'
          }}
          ,{field:'password', title:'密码', width:80}
          ,{field:'nickName', title:'昵称', width:80}
          ,{field:'phone', title:'电话', width:100}
          ,{field:'deviceId', title:'设备ID'}
          ,{field:'status', title:'设备状态', width:100,templet: function(res){
            let menuId = res.id;
            if (res.status == 0) {
                return "<input type='checkbox'  menuId = '" + menuId + "' layui-form-switch lay-filter='status' lay-skin='switch' lay-text='锁定|未锁定'>"
            } else if (res.status == 1) {
                return "<input type='checkbox'  menuId = '" + menuId + "' layui-form-switch lay-filter='status' lay-skin='switch' lay-text='锁定|未锁定' checked>"
            }
          }}
          ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
        ]]
        ,page: true
      });

      /**
         * TODO 监听单选选中 改变状态
         * <p>
         * switch(status) 对应 lay-filter='status'
         */
          form.on('switch(status)', function (data) {
                // console.log(data.elem.attributes['menuId'].nodeValue);
                // console.log(data.elem.checked); // 开关是否开启，true或者false
                let menuId = data.elem.attributes['menuId'].nodeValue;
                let status ;
                if(data.elem.checked){ //true 锁定
                  status = 1;
                }else{
                  status = 0;
                }
                CoreUtil.sendPut("http://localhost:8081/user/lockUserSet/"+menuId+"/"+status,null,function(res){
                  if(status == 1){
                    layer.msg("已锁定", { icon: 1,time: 1000 });
                  }else{
                    layer.msg("已解锁", { icon: 1,time: 1000 });
                  }
                 
                })
            });
        


      //工具栏事件 
      table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
          case 'add':
            // var data = checkStatus.data;
            // layer.alert(JSON.stringify(data));
            openAddUser();
          break;
          case 'batchDelete':
          layer.confirm('真的删除这么多吗?', function(index){
            var ids=[];
            var i = 0;
            var data = checkStatus.data;
            data.forEach(element => {
              ids[i++] = element.id
            });
            CoreUtil.sendDelete("http://localhost:8081/user/batchRemove",ids,function(res){
              layer.msg(res.msg, { icon: 1,time: 2000 });
                setTimeout(function(){
                  window.parent.location.reload();//刷新父页面
                }, 2200);
            })
          });  
            // layer.msg('选中了：'+ data.length + ' 个');
          break;
        };
      });

      //工具条事件
          table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data;
            var id = obj.data.id; //获得当前行数据的id
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            // var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if(layEvent === 'del'){ //删除
              layer.confirm('真的删除行么', function(index){
                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                layer.close(index);
                //向服务端发送删除指令
                CoreUtil.sendDelete("http://localhost:8081/user/"+id,null,function(res){
                  layer.msg(res.msg, { icon: 1,time: 2000 });
                })
              });
            } else if(layEvent === 'edit'){ //编辑
              //do something
              openUpdateUser(data);
             
            } 
          });
      

      var url = "";
      var mainIndex = "";
      //弹出添加用户的页面
      function  openAddUser(){
        mainIndex = layer.open({
          type: 1, 
          title:'添加用户',
          content: $('#saveOrUpdateDiv'),
          skin: 'layui-layer-molv',
          area: ['800px', '300px'],
          // offset: '100px',
          anim: 3,
          resize:false,
          success: function(index){
               $('#dataForm')[0].reset();
              
               url = "add";
          },
          cancel: function(index, layero){ 
            if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
              layer.close(index)
              window.parent.location.reload();//刷新父页面
            }
            return false; 
            }   
        });
      }
       //弹出修改用户的页面
       function  openUpdateUser(data){
        mainIndex = layer.open({
          type: 1, 
          title:'修改用户',
          content: $('#saveOrUpdateDiv'),
          skin: 'layui-layer-molv',
          area: ['800px', '300px'],
          // offset: '100px',
          anim: 1,
          resize:false,
          success: function(index){
               form.val('dataForm',data)
               url = "updata";
          },
          cancel: function(index, layero){ 
            if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
              layer.close(index)
              window.parent.location.reload();//刷新父页面
            }
            return false; 
            }    
         });
      }

     //保存
      form.on('submit(doSubmit)',function(obj){
          console.log(url);
          var params = $('#dataForm').serialize();
          console.log(params)
          //发送ajaxCoreUtil.sendPost
          CoreUtil.sendGet("http://localhost:8081/user/"+url,params,function(res){
            layer.msg(res.msg,{ icon: 1,time: 3000 });
            //关闭弹出层
            layer.close(mainIndex);
            //刷新数据表格
            tableIns.reload();
            window.parent.location.reload();//刷新父页面
          })
          // }

      })

      //条件搜索  
      $(document).on("click","#doSearch",function(res){
          // console.log(tableIns.config);
          // console.log(tableIns.config.limit);
          // console.log(tableIns.config.page.count);
          var page = tableIns.config.page.index;
          var limit = tableIns.config.limit;
          var limit = tableIns.config; 
          var count = tableIns.config.page.count; 
          // var params = $('#searchForm').serialize();
          // var userName =  JSON.stringify($('#userNameSearch').val());
          var userName = $('#userNameSearch').val();
          var userId = $('#userIdSearch').val();
          var startTime = $('#startTimeSearch').val();
          var endTime = $('#endTimeSearch').val();
          //这里的重载有一个未解决的bug 搜索出来的数据不能分页展示 搜索条件为空时只能得到固定页的数据点击不能跳转(原因：page不会动态变化)
          tableIns.reload({
                    elem: '#test',
                    url: "http://localhost:8081/user/list/?page=1&limit="+count,
                    method:"post",
                    cache: false,
                    async: true,
                    contentType: 'application/json; charset=UTF-8',
                    dataType: "json",
                    headers: {
                      'userTicket':sessionStorage.getItem("userTicket"),
                              },
                    // toolbar: '#toolbarDemo',
                      // data: JSON.stringify({params}),
                        where: { //设定异步数据接口的额外参数，任意设
                          userId:userId,
                          userName:userName,
                          startTime:startTime,
                          endTime:endTime,
                          page: {
                              curr: 1 //重新从第 1 页开始
                          }
                      }
                      })
      })      



    });
    </script>
      

</body>
</html>